package com.musemun.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.musemun.common.CommonResult;
import com.musemun.exception.MyDefineException;
import com.musemun.pojo.Employee;
import com.musemun.pojo.EmployeeRepository;
import com.musemun.pojo.Er;
import com.musemun.pojo.Role;
import com.musemun.pojo.Vo.EmployeeHasRole;
import com.musemun.service.EmployeeService;
import com.musemun.service.ErService;
import com.musemun.service.RoleService;
import com.musemun.service.function.functionimpl.BaseEmployee;
import com.musemun.service.function.functionimpl.EmployeeDetailService;
import com.musemun.service.function.functionimpl.EmployeeRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>
 *         写的太快完全没有想过优化的类
 * </p>
 * @author winner
 * @date 2020/5/14
 */
@RestController
@Api(tags="权限增删改查模块")
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    EmployeeService employeeService;
    @Resource
    ErService erService;
    @Resource
    RoleService roleService;
//    roles 29(管理员),30(部门负责人),32(资产科人员),33(仓管员),34(文职人员),38(超级管理员)
    @Resource
    BaseEmployee baseEmployee;

    @PostMapping("/insert")
    @Transactional
    public CommonResult<Employee> insertEmployee(Employee employee){
        Employee employeeExist = baseEmployee.queryByNameEmployeeExist(employee.getEName());
        if(employeeExist!=null){
            throw new MyDefineException(400,"该用户已经存在，请重新选择用户名");
        }
        //md5加密插入账户
        baseEmployee.insertEmployee(employee);


        if(roleBindPermission(employee)){
            return new CommonResult<>(200,employee.getEName()+"已经录入数据库",employee);
        }
        throw new MyDefineException(400,"请输入正确的角色信息,正确的角色包括9(管理员),30(部门负责人),32(资产科人员),33(仓管员),34(文职人员),38(超级管理员)");
    }

    @PostMapping("/update/{id}")
    public CommonResult<Employee> updateEmployee(@NotNull @PathVariable int id,Employee employee){
        Employee employee1 = baseEmployee.queryByIdEmployeeExist(id);
        String role=employee.getRoles();
        if(role!=null&& !role.equals(employee1.getRoles())){
            //删除原来绑定的权限
            erService.deleteErByEnoAndRole(id,employee1.getRoles());
            roleBindPermission(employee.setENo(id));
        }
        return new CommonResult<>(200,employee.getEName()+"已经更新数据库",
                baseEmployee.updateEmployee(employee.setENo(id)));
    }

    @GetMapping("/query_by_id/{id}")
    public CommonResult<EmployeeHasRole> queryEmployeeById(@PathVariable long id){
        return new CommonResult<>(200,"查询成功",
                baseEmployee.queryEmployeeHasRole(id));
    }
    @GetMapping("/query_by_name/{name}")
    public CommonResult<EmployeeHasRole>queryEmployeeByName(@PathVariable String name){
        return new CommonResult<>(200,"成功获取条名字为"+name+"的员工信息",
                baseEmployee.queryEmployeeHasRole(employeeService.
                        getOne(new QueryWrapper<Employee>().eq("eName", name)).getENo()));
    }

    @GetMapping("/query_page/{page}/{size}")
    public CommonResult<List<Employee>>queryEmployeePage(@PathVariable long page,@PathVariable long size){
        Page<Employee> employeePage = new Page<Employee>().setCurrent(page).setSize(size);
        IPage<Employee> page1 = employeeService.page(employeePage, new QueryWrapper<>());
       return new CommonResult<>(200,"查询成功",page1.getRecords());
    }

    @GetMapping("/query_total")
    public CommonResult<Integer>queryTotalSize(){
        Integer count = employeeService.count(new QueryWrapper<>());
        return new CommonResult<>(200,"数据一共"+count+"条",count);
    }

    @Resource
    EmployeeRepository employeeRepository;
    @DeleteMapping("/delete_employee/{id}")
    public CommonResult<String> deleteEmployee(@PathVariable long id){
        Employee employee = baseEmployee.queryByIdEmployeeExist(id);

        employeeService.removeById(id);
        if(employeeRepository.findByUsername(employee.getEName())!=null)
            employeeRepository.remove(employee.getEName());
        return new CommonResult<>(200,
                "删除"+employee.getEName()+"用户成功");
    }
    @Resource
    EmployeeDetailService employeeDetailService;
    @PostMapping("/insert_permission/{id}/{roleid}")
    @ApiOperation("传入角色的id,和角色权限的id,增加用户的权限")
    public CommonResult<String> insertEmployeePermission(@PathVariable Integer id, @PathVariable Integer roleid){
        if(!queryErExist(id,roleid)){
            throw new MyDefineException(403,"用户已经存在此权限不需要插入");
        }
        queryErExist(id,roleid);
        String eName = null;
        try{
            eName = baseEmployee.queryByIdEmployeeExist(id).getEName();
            erService.save(new Er(id, roleid));
            return new CommonResult<>(200,eName+"用户权限插入成功");
        }catch (Exception e){
            throw new MyDefineException(403,baseEmployee.queryByIdEmployeeExist(id).getEName()+"权限插入失败，请设置正确的权限");
        }finally {
            Employee employee = employeeDetailService.loadUserByUsername(eName);
            employeeRepository.remove(employee.getEName());
            employeeRepository.insert(employee);
        }


    }

    @PostMapping("/delete_permission/{id}/{roleid}")
    @ApiOperation("传入角色的id,和角色权限的id，删除用户的权限, 29(管理员),30(部门负责人),32(资产科人员),33(仓管员),34(文职人员),38(超级管理员)")
    public CommonResult<EmployeeHasRole> deleteEmployeePermission(@PathVariable Integer id,@PathVariable Integer roleid){
        if(queryErExist(id,roleid)){
            throw new MyDefineException(403,"用户不存在此权限");
        }
        String eName = null;
        try{
            eName = baseEmployee.queryByIdEmployeeExist(id).getEName();
            erService.remove(new QueryWrapper<Er>().and(data -> data.eq("eNo", id).eq("rid", roleid)));
            return new CommonResult<>(200,eName+"用户权限删除成功");
        }catch (Exception e){
            throw new MyDefineException(403,
                    "权限删除失败，"+eName+"用户可能不存在此的权限,或者不存在此用户");
        }finally {
            Employee employee = employeeDetailService.loadUserByUsername(eName);
            employeeRepository.remove(employee.getEName());
            employeeRepository.insert(employee);
        }

}


    public Boolean queryErExist(Integer id,Integer roleid){
        Er one = erService.getOne(new QueryWrapper<Er>().and(data -> data.eq("eNo", id).eq("rid", roleid)));
        return one == null;
    }




    public Boolean roleBindPermission(Employee employee){
        Role role = roleService.getOne(new QueryWrapper<Role>().eq("role", employee.getRoles()));
        return erService.save(new Er(employee.getENo(),role.getRid()));
    }
}
